package pro.softzhang.algo.lc500;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO 加练
 */
public class LC525_ContiguousArray {
    public static void main(String[] args) {
        int[] nums = {0,0,1,0,0,0,1,1};
        int len = new LC525_Solution().findMaxLength(nums);
        System.out.println(len);
    }
}

class LC525_Solution {
    public int findMaxLength(int[] nums) {
        int max = 0, sum = 0;
        Map<Integer, Integer> preSum = new HashMap<>();
        preSum.put(0, -1);
        for (int i = 0; i < nums.length; i++){
            sum += nums[i] == 0 ? -1 : 1;
            if(preSum.containsKey(sum)) {
                max = Math.max(max, i - preSum.get(sum));
            } else {
                preSum.put(sum, i);
            }
        }
        return max;
    }
}
